package com.fenger.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @PackageName: com.fenger.filter
 * @ClassName: LoginFilter
 * @Description:
 * @author: fang
 * @date: 2021/10/31 20:10
 */
public class LoginFilter implements Filter {
    public static final String TOKEN = "xx";
    private static final Set<String> EXECUTE_URL_SET = new HashSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String executeUrl = filterConfig.getInitParameter("executeUrl");
        if (null != executeUrl) {
            String[] split = executeUrl.split(";");
            EXECUTE_URL_SET.addAll(Arrays.asList(split));
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = ((HttpServletRequest) servletRequest).getCookies();
        StringBuffer requestURL = ((HttpServletRequest) servletRequest).getRequestURL();
        String requestUrl = requestURL.toString();
        boolean isExecute = false;
        for (String url : EXECUTE_URL_SET) {
            if (requestUrl.endsWith(url)) {
                isExecute = true;
            }
        }
        if (isExecute) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        Map<String, String> map = new HashMap<>();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                map.put(cookie.getName(), cookie.getValue());
            }
        }
        String token = map.getOrDefault("token", "");
        if (TOKEN.equals(token)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.getRequestDispatcher("page").forward(servletRequest, servletResponse);
            return;
        }
    }

    @Override
    public void destroy() {
    }
}
